/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2009 - 2012 Luca Mingardi.
 *
 * This file is part of jeeObserver.
 *
 * JeeObserver is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * JeeObserver is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
package jeeobserver;

import java.util.logging.Level;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import jeeobserver.server.JeeObserverServerException;

/**
 * The Class JeeObserverListener.
 *
 * <p>
 * This servlet context listener create a new jeeObserver context (if not
 * exists) into current JVM instance.
 * </p>
 *
 * @author Luca Mingardi
 * @version 4.0
 */
public class JeeObserverListener implements ServletContextListener {

	/** The applications count. */
	private static int applicationsCount = 0;

	/**
	 *
	 * @param event
	 */
	@Override
	public void contextDestroyed(ServletContextEvent event) {

		if (JeeObserverListener.applicationsCount > 0) {
			JeeObserverListener.applicationsCount = JeeObserverListener.applicationsCount - 1;
		}

		if (JeeObserverListener.applicationsCount <= 0) {
			try {
				if ((JeeObserverContext.getInstance() != null) && JeeObserverContext.getInstance().isEnabled()) {
					JeeObserverContext.getInstance().close();
				}
			} catch (final JeeObserverServerException e) {
				JeeObserverContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}
		}
	}

	/**
	 *
	 * @param event
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		if (JeeObserverListener.applicationsCount <= 0) {
			try {
				JeeObserverContext.createInstance();
			} catch (final Exception e) {
				JeeObserverContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}
		}

		JeeObserverListener.applicationsCount = JeeObserverListener.applicationsCount + 1;

	}
}
